import React, { Component, Fragment } from 'react'
import propTypes from 'prop-types' // 类型检测
import { Input, Button } from 'antd'
const { Search } = Input;

export default class NpyItem extends Component {

  constructor(props) {
    super(props)
    this.state = {
      isEditing: false,
      inputValue: '',
    }
  }
  // // 已废弃，推荐使用componentDidUpdate代替
  // componentWillReceiveProps(newProps) {
  //   console.log('chilld---componentWillReceiveProps---组件接收新属性时调用---', newProps)
  // }
  shouldComponentUpdate(nextProps, nextState) {
    if (nextProps.ctn !== this.props.ctn) {
      return true
    } else {
      return false
    }
  }
  componentDidUpdate(prevProps, prevState) {
    if (prevProps.ctn !== this.props.ctn) {
      console.log('---监听组件内部状态的变化---', prevProps, prevState, this.props.ctn)
    }
  }
  // componentWillUpdate() {
  //   // console.log('child---componentWillUpdate---')
  // }
  render() {
    const { isEditing } = this.state
    return (
      <Fragment>
        {isEditing ?
          <Search id="todo"
            className="input"
            onChange={this.inputChange.bind(this)}
            enterButton="确定"
            value={this.state.inputValue}
            onSearch={this.handleEdit.bind(this)}
          />
          :
          <Fragment>
            <span>{this.props.ctn === '' ? '空任务' : this.props.ctn}</span>
            <Button className="ml-10 blue csp" onClick={this.showEditInput.bind(this)} type="primary" size="small">修改</Button>
            <Button className="ml-10 red csp" onClick={this.handleClick.bind(this)} type="primary" danger size="small">删除</Button>
          </Fragment>
        }
      </Fragment>
    )
  }
  // componentDidUpdate() {
  //   console.log('child---componentDidUpdate---')
  // }
  // componentWillUnmount() {
  //   console.log('child---componentWillUnmount---组件卸载')
  // }
  inputChange(e) {
    let val = e.target.value
    this.setState({
      inputValue: val
    })
    this.forceUpdate()
  }
  handleClick() {
    this.props.deval(this.props.idx)
  }
  showEditInput() {
    this.setState({
      isEditing: true,
      inputValue: this.props.ctn,
    })
    this.forceUpdate()
  }
  handleEdit() {
    this.setState({
      isEditing: false,
    })
    this.forceUpdate()
    this.props.editval(this.props.idx, this.state.inputValue)
  }
}

// 类型检测
NpyItem.propTypes = {
  ctn: propTypes.string,
  deval: propTypes.func,
  editval: propTypes.func,
  idx: propTypes.number,
  avname: propTypes.string.isRequired
}
// 设定默认值
NpyItem.defaultProps = {
  avname: ""
}
